package iscas;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import java.util.function.Consumer;

@SuppressWarnings("unused")
public class RedisConfig {
    public static String addr = "133.133.135.56";

    public static Jedis newJedis() {
        return new Jedis(addr, 6379);
    }

    public static void subscribe(Consumer<String> act, String channel) {
        JedisPubSub pubSub = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                System.out.printf("[ISCAS][subscribe] %s in %s\n", message, channel);
                if (message.equals("exit")) {
                    this.unsubscribe(channel);
                } else {
                    act.accept(message);
                }
            }

            @Override
            public void onUnsubscribe(String channel, int subscribedChannels) {
                System.out.printf("[ISCAS][JedisPubSub] %s exit\n", channel);
            }
        };
        new Thread(() -> {
            Jedis jedis = newJedis();
            jedis.subscribe(pubSub, channel);
            jedis.close();
        }).start();
    }

    public static String getOrDefault(Jedis jedis, String key, String value) {
        String s = jedis.get(key);
        return s == null ? value : s;
    }
}
